# 根据股票代码获取最新第一个交易日的分钟数据

# 导入 efinance 如果没有安装则需要通过执行命令: pip install efinance 来安装
import efinance as ef
import pandas as pd
import schedule
import time

def single_handle(stock_code, df):
    # print(f"\n股票代码：{stock_code}")
    rise = False
    # 遍历df的每一行
    last_row = None
    for index, row in df.iterrows():
        # 红线
        if last_row is not None and row['开盘'] < row['收盘']:
            last_high = last_row['开盘'] if last_row['开盘'] < last_row['收盘'] else last_row['收盘']
            if last_high+0.003 < row['收盘']:
                if not rise:
                    rise = True
                    # print("↑↑↑", row['日期'], row['收盘'])
                    send_alarm(index, df.shape[0], rise, row)
                else:
                    # print("\t续涨", row['日期'], row['收盘'])
                    pass
        else:
            if rise:
                # print("转跌", row['日期'], row['收盘'])
                rise = False
                send_alarm(index, df.shape[0], rise, row)
        last_row = row

def send_alarm(index, df_row_num, rise, row):
    if index == df_row_num-2:
        last_date = row['日期']
        # 判断last_date 与当前时间的差值不大于1小时，则发送邮件
        if (pd.to_datetime(last_date)- pd.Timestamp.now()).total_seconds() < 3600:
            subject = ("↑↑↑转涨：" if rise == True else "↓↓↓转跌：") + row['股票名称']
            send_mail(subject, f"{row}")
            print(f"\n{subject}\n---------------------------------\n{row}")
    
def send_mail(subject, content):
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import parseaddr, formataddr

    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    # 发件人和收件人的邮箱地址
    sender = 'gjhuai@qq.com'
    receiver = 'gjhuai@qq.com'

    # 创建邮件对象
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = _format_addr('GJH <%s>' % sender)  
    # Header(f"{sender_name} <{sender}>", 'utf-8')
    message['To'] = _format_addr('Trader <%s>' % receiver)
    # Header(f"Joe <{receiver}>", 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')

    # 登录QQ邮箱的SMTP服务器
    smtp_server = 'smtp.qq.com'
    smtp_port = 465
    password = 'gjnxbqqagvhrbiae'

    # 发送邮件
    try:
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(sender, password)
        server.sendmail(sender, [receiver], message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print("Error: 无法发送邮件", e)
    finally:
        server.quit()
        

def main():
    stock_code_list = ['159783','002415']
    # 60 分钟线
    freq = 60
    # 获取最新一个交易日的分钟级别股票行情数据
    df_map = ef.stock.get_quote_history(stock_code_list, klt=freq)

    for stock_code, df in df_map.items():
        single_handle(stock_code, df)
        print(f'股票名称: {ef.stock.get_quote(stock_code)["name"]}')

if __name__ == '__main__':
    # 在9:00, 10:33, 11:33, 14:03 四个时间点执行main()
    schedule.every().day.at("09:00").do(main)
    schedule.every().day.at("10:33").do(main)
    schedule.every().day.at("11:33").do(main)
    schedule.every().day.at("14:03").do(main)

    # 持续检查并执行计划任务
    while True:
        schedule.run_pending()
        time.sleep(20)

    
    # send_mail("test标题", "内容")

# 将数据存储到 csv 文件中
# df.to_csv(f'{stock_code}-30.csv', encoding='utf-8-sig', index=None)
# print(f'股票: {stock_code} 的行情数据已存储到文件: {stock_code}.csv 中！')

# df = pd.read_csv(f'{stock_code}-30.csv')
# columns_ab = df[['日期', '收盘']]
# print(columns_ab)

# 找出"开盘"数值大于上一行的"最高"数值的行
# df_down = df[(df['开盘']<df['收盘']) & (df['收盘'] >= (df['开盘'].shift(1) if df['开盘'].shift(1)> df['收盘'].shift(1) else df['收盘'].shift(1)+0.005))]
# print(df_down[['日期', '收盘']])

# 找出"收盘"数值大于上一行的"收盘"数值且小于下一行的"收盘"数值的行
# df_up = df[(df['收盘'] > df['收盘'].shift(1)) & (df['收盘'] < df['收盘'].shift(-1))]
# df_up.to_csv(f'{stock_code}-up.csv', encoding='utf-8-sig', index=None)
# print(df_up[['日期', '收盘']])


